package handlers

import (
	"encoding/json"
	"log/slog"

	"lsp-server/internal/protocol"
)

const DidOpenTextDocumentNotification = "textDocument/didOpen"

type DidOpen struct {
	documentUpdates chan protocol.TextDocumentItem
}

func NewDidOpen(documentUpdates chan protocol.TextDocumentItem) *DidOpen {
	return &DidOpen{documentUpdates: documentUpdates}
}

func (d DidOpen) Call(params json.RawMessage) error {
	slog.Info("received didOpen notification")
	openParams, err := d.parseParams(params)
	if err != nil {
		slog.Error("Error to parse didOpen params")
		return err
	}
	slog.Debug("didOpen params", slog.Any("params", *openParams))
	d.documentUpdates <- openParams.TextDocument

	return nil
}

func (d DidOpen) parseParams(params json.RawMessage) (*protocol.DidOpenTextDocumentParams, error) {
	var openParams protocol.DidOpenTextDocumentParams
	if err := json.Unmarshal(params, &openParams); err != nil {
		return nil, err
	}

	return &openParams, nil
}
